//
//  BCSVIPController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/28.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCSVIPController.h"

//vc
#import "BCURLController.h"
#import "BCSvipBuyController.h"

//views
#import "BCUserSvipHeaderView.h"
//cell
#import "BCUserNoSvipContentCell.h"
#import "BCUserNoSvipTitleCell.h"
#import "BCSvipMenberHeaderView.h"
#import "BCSvipMenberRewardCell.h"

//request
#import "BCUserSvipRequest.h"

@interface BCSVIPController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *svipTable;

/**
 *BCUserSvipHeaderView
 */
@property (nonatomic, strong) BCUserSvipHeaderView *headView;

#pragma mark - data

/**
 *BCUserSvipData
 */
@property (nonatomic, strong) BCUserSvipData *svipData;

@end

@implementation BCSVIPController

- (BCUserSvipHeaderView *)headView {
    if (!_headView) {
        CGFloat width = CGRectGetWidth(self.view.frame);
        CGFloat height = [BCUserSvipHeaderView heightWithWidth:width];
        _headView = [[BCUserSvipHeaderView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        [_headView addBuyTarget:self action:@selector(buySvipDidClickedAction)];
    }
    return _headView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self requestSvipDataInit:true refresh:false];
}

- (void)setupSubviews {
    self.customNaviBar.backgroundColor = [BCUserSvipHeaderView sepColor];
    //
    BCUserSvipGradientView *naviGradientView = [[BCUserSvipGradientView alloc] init];
    naviGradientView.gradientColors = @[[BCUserSvipHeaderView topColor],[BCUserSvipHeaderView sepColor]];
    [self.customNaviBar insertSubview:naviGradientView atIndex:0];
    [naviGradientView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.customNaviBar);
    }];
    //
    self.svipTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.svipTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.svipTable.dataSource = self;
    self.svipTable.delegate = self;
    self.svipTable.showsHorizontalScrollIndicator = false;
    self.svipTable.showsVerticalScrollIndicator = false;
    [self.view addSubview:self.svipTable];
    [self.svipTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    //
    [self.svipTable registerClass:BCUserNoSvipTitleCell.class forCellReuseIdentifier:NSStringFromClass(BCUserNoSvipTitleCell.class)];
    [self.svipTable registerClass:BCUserNoSvipContentCell.class forCellReuseIdentifier:NSStringFromClass(BCUserNoSvipContentCell.class)];
    //
    [self.svipTable registerClass:BCSvipMenberHeaderView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(BCSvipMenberHeaderView.class)];
    [self.svipTable registerClass:BCSvipMenberRewardCell.class forCellReuseIdentifier:NSStringFromClass(BCSvipMenberRewardCell.class)];
    //
    if (Height_Bottom_SafeArea>0) {
        UIView *safeFooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, Height_Bottom_SafeArea)];
        [self.svipTable setTableFooterView:safeFooter];
    }
    
    //
    [self.view layoutIfNeeded];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    BCUserSvipData *data = self.svipData;
    if (data) {
        if (data.data.has_svip) {
            return data.currentShares.content.count;
        }else {
            NSInteger titleCount = 0;
            if (data.content.title.length) {
                titleCount = 1;
            }
            return data.content.content.count+titleCount;
        }
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCUserSvipData *data = self.svipData;
    if (data) {
        if (data.data.has_svip) {
            BCSvipMenberRewardCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCSvipMenberRewardCell.class)];
            cell.svipData = data;
            if (data.currentShares&&data.currentShares.content.count>indexPath.row) {
                cell.content = data.currentShares.content[indexPath.row];
            }
            return cell;
        }else {
            NSString *title = data.content.title;
            BOOL hasTitle = (title.length!=0);
            if (hasTitle&&indexPath.row==0) {
                BCUserNoSvipTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCUserNoSvipTitleCell.class)];
                cell.tableView = tableView;
                cell.title = title;
                return cell;
            }else {
                BCUserSvipDataContentModel *model = data.content.content[indexPath.row-(hasTitle?1:0)];
                //
                BCUserNoSvipContentCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCUserNoSvipContentCell.class)];
                cell.content = model;
                return cell;
            }
        }
    }
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    BCUserSvipData *data = self.svipData;
    if (data) {
        if (data.data.has_svip&&data.shares.count) {
            BCSvipMenberHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(BCSvipMenberHeaderView.class)];
            headerView.tableView = tableView;
            headerView.svipData = data;
            return headerView;
        }
    }
    return nil;
}
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCUserSvipData *data = self.svipData;
    if (data) {
        if (data.data.has_svip) {
            return [BCSvipMenberRewardCell defaultHeight];
        }else {
            NSString *title = data.content.title;
            BOOL hasTitle = (title.length!=0);
            if (hasTitle&&indexPath.row==0) {
                return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCUserNoSvipTitleCell.class) configuration:^(id cell) {
                    ((BCUserNoSvipTitleCell *)cell).title = title;
                }];
            }else {
                BCUserSvipDataContentModel *model = data.content.content[indexPath.row-(hasTitle?1:0)];
                return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCUserNoSvipContentCell.class) configuration:^(id cell) {
                    ((BCUserNoSvipContentCell *)cell).content = model;
                }];
            }
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    BCUserSvipData *data = self.svipData;
    if (data) {
        if (data.data.has_svip) {
            return [BCSvipMenberHeaderView heightWithWidth:tableView.frame.size.width];
        }
    }
    return 0;
}

#pragma mark - action
- (void)didClickedNaviRightButton {
    BCURLController *detail = [BCURLController new];
    detail.urlString = self.svipData.flow.left_url_text;
    [self.navigationController pushViewController:detail animated:true];
}

#pragma mark - request
/**
 请求数据
 */
- (void)requestSvipDataInit:(BOOL)init refresh:(BOOL)refresh {
    if (init) {
        [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    }
    BCUserSvipRequest *request = [BCUserSvipRequest new];
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserSvipResponse *resp = result;
        [wself handleSvipData:resp.data init:init refresh:refresh];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            if (init) {
                [wself.view bc_showWithInsets:UIEdgeInsetsMake(CGRectGetHeight(wself.customNaviBar.frame), 0, 0, 0) error:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitFailedAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitFailedAction {
    [self.view bc_hiddenError];
    [self requestSvipDataInit:true refresh:false];
}

/**
 成功后处理数据
 */
- (void)handleSvipData:(BCUserSvipData *)svipData init:(BOOL)init refresh:(BOOL)refresh {
    if (svipData) {
        //
        self.title = svipData.flow.title;
        if (svipData.flow.left_url_text.length) {
            [self.customNaviBar.rightButton setTitle:svipData.flow.left_button forState:UIControlStateNormal];
            [self.customNaviBar layoutSubviews];
        }
    }
    //
    self.svipData = svipData;
    
}
- (void)setSvipData:(BCUserSvipData *)svipData {
    _svipData = svipData;
    //
    if (_svipData) {
        self.svipTable.tableHeaderView = self.headView;
        self.headView.svipData = _svipData;
        //
        if (_svipData.data.has_svip) {
            //设置第一个为选中
            if (_svipData.shares.count) {
                BCUserSvipDataShares *first = _svipData.shares[0];
                //
                first.selectFlag = true;
                _svipData.currentShares = first;
            }
        }
        
    }else {
        self.svipTable.tableHeaderView = nil;
    }
    [self.svipTable reloadData];
}

#pragma mark - actions
/**
 点击了立即购买SVIP
 */
- (void)buySvipDidClickedAction {
    WEAK_SELF
    [BCSvipBuyController showBuyFromController:self.navigationController data:self.svipData complete:^(NSString * _Nonnull successMsg) {
        if (wself.view&&successMsg.length) {
            [QMUITips showSucceed:successMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:successMsg]];
        }
        [wself handleBuySvipSuccess];
        
        //
        if (wself.delegate && [wself.delegate respondsToSelector:@selector(buySVIPSuccessedAction)]) {
            [wself.delegate buySVIPSuccessedAction];
        }
    }];
}
/**
 购买SVIP成功刷新界面
 */
- (void)handleBuySvipSuccess {
    self.svipData = nil;
    [self.customNaviBar.rightButton setTitle:nil forState:UIControlStateNormal];
    self.svipTable.tableHeaderView = nil;
    [self.svipTable reloadData];
    //
    [self requestSvipDataInit:true refresh:false];
}


@end
